import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:family_app/src/theme/app_theme.dart';

/// 记账屏幕
/// 用于记录收入和支出
class AccountingScreen extends ConsumerStatefulWidget {
  const AccountingScreen({Key? key}) : super(key: key);

  @override
  ConsumerState<AccountingScreen> createState() => _AccountingScreenState();
}

class _AccountingScreenState extends ConsumerState<AccountingScreen> {
  /// 是否为支出（true: 支出, false: 收入）
  bool isExpense = true;

  /// 选中的分类
  String selectedCategory = '';

  /// 金额文本
  String amountText = '0';

  /// 备注文本
  String remarkText = '';

  /// 分类列表
  final List<Map<String, dynamic>> categories = [
    {'name': '餐饮', 'icon': '🍽️'},
    {'name': '购物', 'icon': '🛍️'},
    {'name': '交通', 'icon': '🚗'},
    {'name': '娱乐', 'icon': '🎮'},
    {'name': '生活', 'icon': '💡'},
    {'name': '医疗', 'icon': '⚕️'},
    {'name': '教育', 'icon': '📚'},
    {'name': '其他', 'icon': '📦'},
  ];

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 8.h),
      child: Column(
        children: [
          // 支出/收入切换
          _buildTypeToggle(),
          SizedBox(height: 10.h),

          // 金额显示
          _buildAmountDisplay(),
          SizedBox(height: 10.h),

          // 分类选择
          Expanded(
            flex: 2, // 分类占用更多空间
            child: _buildCategoryGrid(),
          ),

          // 备注输入模块
          _buildRemarkInput(),

          // 数字键盘
          Expanded(
            flex: 3, // 键盘占用主要空间
            child: _buildNumberKeyboard(),
          ),

          // 确认按钮
          _buildSubmitButton(),
        ],
      ),
    );
  }

  /// 构建支出/收入切换
  Widget _buildTypeToggle() {
    return Container(
      decoration: BoxDecoration(
        color: Colors.grey[100],
        borderRadius: BorderRadius.circular(10.r),
        border: Border.all(color: Colors.grey[200]!),
      ),
      padding: EdgeInsets.all(3.w),
      child: Row(
        children: [
          // 支出按钮
          Expanded(
            child: GestureDetector(
              onTap: () => setState(() => isExpense = true),
              child: Container(
                padding: EdgeInsets.symmetric(vertical: 8.h),
                decoration: BoxDecoration(
                  color: isExpense ? AppTheme.primaryColor : Colors.transparent,
                  borderRadius: BorderRadius.circular(8.r),
                ),
                child: Text(
                  '支出',
                  textAlign: TextAlign.center,
                  style: TextStyle(
                    color: isExpense ? Colors.white : Colors.grey[600],
                    fontWeight: FontWeight.w600,
                    fontSize: 12.sp,
                  ),
                ),
              ),
            ),
          ),

          // 收入按钮
          Expanded(
            child: GestureDetector(
              onTap: () => setState(() => isExpense = false),
              child: Container(
                padding: EdgeInsets.symmetric(vertical: 8.h),
                decoration: BoxDecoration(
                  color: !isExpense ? AppTheme.primaryColor : Colors.transparent,
                  borderRadius: BorderRadius.circular(8.r),
                ),
                child: Text(
                  '收入',
                  textAlign: TextAlign.center,
                  style: TextStyle(
                    color: !isExpense ? Colors.white : Colors.grey[600],
                    fontWeight: FontWeight.w600,
                    fontSize: 12.sp,
                  ),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  /// 构建金额显示
  Widget _buildAmountDisplay() {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.h),
      decoration: BoxDecoration(
        color: Colors.grey[50],
        borderRadius: BorderRadius.circular(10.r),
        border: Border.all(color: Colors.grey[200]!),
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Text(
            '¥',
            style: TextStyle(
              fontSize: 18.sp,
              fontWeight: FontWeight.w500,
              color: AppTheme.primaryColor,
            ),
          ),
          SizedBox(width: 8.w),
          Text(
            amountText,
            style: TextStyle(
              fontSize: 32.sp,
              fontWeight: FontWeight.w300,
              color: Colors.black87,
            ),
          ),
        ],
      ),
    );
  }

  /// 构建分类网格
  Widget _buildCategoryGrid() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Padding(
          padding: EdgeInsets.only(bottom: 6.h),
          child: Text(
            '选择分类',
            style: TextStyle(
              fontSize: 12.sp,
              fontWeight: FontWeight.w600,
              color: Colors.black87,
            ),
          ),
        ),
        Expanded(
          child: GridView.builder(
            shrinkWrap: true,
            physics: const ScrollPhysics(),
            gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
              crossAxisCount: 4,
              crossAxisSpacing: 8.w,
              mainAxisSpacing: 20.w,
              childAspectRatio: 1.2,//子项宽高比
            ),
            itemCount: categories.length,
            itemBuilder: (context, index) {
              final category = categories[index];
              final isSelected = selectedCategory == category['name'];

              return GestureDetector(
                onTap: () => setState(() => selectedCategory = category['name']),
                child: Container(
                  decoration: BoxDecoration(
                    color: isSelected ? AppTheme.primaryColor : Colors.grey[100],
                    borderRadius: BorderRadius.circular(10.r),
                    border: isSelected
                        ? Border.all(color: AppTheme.primaryColor, width: 2)
                        : Border.all(color: Colors.grey[200]!),
                    boxShadow: isSelected
                        ? [
                            BoxShadow(
                              color: AppTheme.primaryColor.withOpacity(0.2),
                              blurRadius: 6,
                              offset: const Offset(0, 1),
                            ),
                          ]
                        : null,
                  ),
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Text(
                        category['icon'],
                        style: TextStyle(fontSize: 24.sp),
                      ),
                      SizedBox(height: 4.h),
                      Text(
                        category['name'],
                        style: TextStyle(
                          color: isSelected ? Colors.white : Colors.black87,
                          fontSize: 10.sp,
                          fontWeight: FontWeight.w500,
                        ),
                        textAlign: TextAlign.center,
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                      ),
                    ],
                  ),
                ),
              );
            },
          ),
        ),
      ],
    );
  }

  /// 构建备注输入模块
  Widget _buildRemarkInput() {
    return SizedBox(
      height: 50.h, // 固定紧凑高度
      child: Container(
        padding: EdgeInsets.symmetric(vertical: 4.h),
        color: Colors.white,
        child: Row(
          children: [
            // 输入框（占横向2/3）
            Expanded(
              flex: 2,
              child: TextField(
                controller: TextEditingController(text: remarkText),
                onChanged: (value) => setState(() => remarkText = value),
                decoration: InputDecoration(
                  hintText: '添加备注（可选）',
                  hintStyle: TextStyle(
                    color: Colors.grey[400],
                    fontSize: 14.sp,
                  ),
                  contentPadding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 8.h),
                  border: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(8.r),
                    borderSide: BorderSide(color: Colors.grey[300]!),
                  ),
                  enabledBorder: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(8.r),
                    borderSide: BorderSide(color: Colors.grey[300]!),
                  ),
                  focusedBorder: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(8.r),
                    borderSide: BorderSide(color: AppTheme.primaryColor),
                  ),
                ),
                style: TextStyle(
                  fontSize: 14.sp,
                  color: Colors.black87,
                ),
              ),
            ),

            SizedBox(width: 8.w),

            // 拍照图标（占横向1/3）
            Expanded(
              flex: 1,
              child: GestureDetector(
                onTap: () {
                  // TODO: 实现拍照功能
                  ScaffoldMessenger.of(context).showSnackBar(
                    const SnackBar(
                      content: Text('拍照功能待实现'),
                      duration: Duration(seconds: 2),
                    ),
                  );
                },
                child: Container(
                  height: 40.h,
                  decoration: BoxDecoration(
                    color: AppTheme.primaryColor.withOpacity(0.1),
                    borderRadius: BorderRadius.circular(8.r),
                    border: Border.all(color: AppTheme.primaryColor.withOpacity(0.3)),
                  ),
                  child: Icon(
                    Icons.camera_alt,
                    color: AppTheme.primaryColor,
                    size: 20.sp,
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// 构建数字键盘
  Widget _buildNumberKeyboard() {
    final buttons = [
      '1', '2', '3',
      '4', '5', '6',
      '7', '8', '9',
      '.', '0', '⌫',
    ];

    return Container(
      color: Colors.white,
      child: GridView.builder(
        shrinkWrap: true,
        physics: const ScrollPhysics(),
        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 3,
          crossAxisSpacing: 10.w,
          mainAxisSpacing: 6.w,
          childAspectRatio: 2,
        ),
        itemCount: buttons.length,
        itemBuilder: (context, index) {
          final button = buttons[index];
          final isDeleteButton = button == '⌫';

          return GestureDetector(
            onTap: () => _handleKeyboardInput(button),
            child: Container(
              decoration: BoxDecoration(
                color: isDeleteButton
                    ? Colors.red.withOpacity(0.15)
                    : Colors.grey[100],
                borderRadius: BorderRadius.circular(8.r),
                border: Border.all(
                  color: isDeleteButton
                      ? Colors.red.withOpacity(0.4)
                      : Colors.grey[200]!,
                  width: 1.5,
                ),
                boxShadow: [
                  BoxShadow(
                    color: Colors.black.withOpacity(0.05),
                    blurRadius: 3,
                    offset: const Offset(0, 1),
                  ),
                ],
              ),
              child: Material(
                color: Colors.transparent,
                child: InkWell(
                  onTap: () => _handleKeyboardInput(button),
                  borderRadius: BorderRadius.circular(8.r),
                  child: Center(
                    child: Text(
                      button,
                      style: TextStyle(
                        fontSize: 13.sp,
                        fontWeight: FontWeight.w600,
                        color: isDeleteButton
                            ? Colors.red[600]
                            : Colors.black87,
                      ),
                    ),
                  ),
                ),
              ),
            ),
          );
        },
      ),
    );
  }

  /// 构建确认按钮
  Widget _buildSubmitButton() {
    return SizedBox(
      width: double.infinity,
      child: ElevatedButton(
        onPressed: _submitAccounting,
        style: ElevatedButton.styleFrom(
          backgroundColor: AppTheme.primaryColor,
          padding: EdgeInsets.symmetric(vertical: 10.h),
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(10.r),
          ),
          elevation: 2,
        ),
        child: Text(
          '确认记账',
          style: TextStyle(
            fontSize: 14.sp,
            fontWeight: FontWeight.w600,
            color: Colors.white,
          ),
        ),
      ),
    );
  }

  /// 处理键盘输入
  void _handleKeyboardInput(String input) {
    setState(() {
      if (input == '⌫') {
        // 删除最后一位
        if (amountText.length > 1) {
          amountText = amountText.substring(0, amountText.length - 1);
        } else {
          amountText = '0';
        }
      } else if (input == '.') {
        // 添加小数点
        if (!amountText.contains('.')) {
          amountText += '.';
        }
      } else {
        // 添加数字
        if (amountText == '0') {
          amountText = input;
        } else {
          amountText += input;
        }
      }
    });
  }

  /// 提交记账
  void _submitAccounting() {
    // 验证分类
    if (selectedCategory.isEmpty) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: const Text('请选择分类'),
          backgroundColor: Colors.red,
          duration: const Duration(seconds: 2),
        ),
      );
      return;
    }

    // 验证金额
    final amount = double.tryParse(amountText);
    if (amount == null || amount <= 0) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: const Text('请输入有效金额'),
          backgroundColor: Colors.red,
          duration: const Duration(seconds: 2),
        ),
      );
      return;
    }

    // 显示成功提示
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(
          '记账成功: $selectedCategory - ¥$amount${remarkText.isNotEmpty ? ' - 备注: $remarkText' : ''} - ${isExpense ? '支出' : '收入'}',
        ),
        backgroundColor: Colors.green,
        duration: const Duration(seconds: 2),
      ),
    );

    // 重置表单
    setState(() {
      selectedCategory = '';
      amountText = '0';
      remarkText = ''; // 重置备注
    });
  }
}
